package org.keyroy.util;

public class ObjectPool<E extends Object> {
	private Class<E> class1;
	private Object[] objs;
	private int size;

	public ObjectPool(Class<E> class1) {
		this(class1, 24);
	}

	public ObjectPool(Class<E> class1, int size) {
		try {
			objs = new Object[size];
			for (int i = 0; i < objs.length; i++) {
				objs[i] = class1.newInstance();
			}
			this.class1 = class1;
			this.size = size;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	public final E get() {
		if (size > 0) {
			size -= 1;
			return (E) objs[size];
		} else {
			try {

				try {
					System.out.println("ObjectPool over pool , create : " + class1.getSimpleName());
					new IllegalArgumentException("object may not recycled");
				} catch (Exception e) {
					e.printStackTrace();
				}

				return class1.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public final void recycle(E e) {
		if (size < objs.length) {
			objs[size] = e;
			size++;
		}
	}
}
